package com.zudada.servermain.Service.ServiceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zudada.servermain.POJO.DTO.PortUserDTO;
import com.zudada.servermain.POJO.DTO.PortUserPageQueryDTO;
import com.zudada.servermain.POJO.VO.PageResult;
import com.zudada.servermain.POJO.entity.PortUser;
import com.zudada.servermain.POJO.entity.User;
import com.zudada.servermain.Service.PortUserService;
import com.zudada.servermain.common.constant.PortUserMessageConstant;
import com.zudada.servermain.exception.BusinessException;
import com.zudada.servermain.mapper.PortUserMapper;
import com.zudada.servermain.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;


@Slf4j
@Service
public class PortUserServiceImpl implements PortUserService {

    @Autowired
    private PortUserMapper portUserMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 新增港口人员
     * @param portUserDTO 港口人员信息
     */
    public void save(PortUserDTO portUserDTO) {
        try {
            PortUser portUser = new PortUser();

            // 属性拷贝
            BeanUtils.copyProperties(portUserDTO,portUser);
            portUser.setRegisterTime(LocalDateTime.now());

            portUserMapper.insert(portUser);

            String userId = portUser.getUserId();
            User user = new User();
            user.setUserId(userId);
            user.setRole(portUserDTO.getRole());
            user.setRoleType(portUserDTO.getRoleType());

            userMapper.insert(user);
        } catch (DataIntegrityViolationException e) {
            log.error("新增港口人员失败，数据完整性约束异常：{}", e.getMessage());
            // 处理唯一约束异常（用户名已存在等）
            if (e.getMessage() != null && e.getMessage().contains("unique")) {
                throw new BusinessException(PortUserMessageConstant.USER_ALREADY_EXISTS);
            }
            throw new BusinessException(PortUserMessageConstant.SAVE_FAILED);
        } catch (Exception e) {
            log.error("新增港口人员失败，未知异常：{}", e.getMessage(), e);
            throw new BusinessException(PortUserMessageConstant.SAVE_FAILED);
        }
    }

    /**
     * 根据id删除港口人员
     * @param userId 用户ID
     */
    public void deleteByUserId(String userId) {
        // 业务规则校验：用户ID不能为空
        if (!StringUtils.hasText(userId)) {
            throw new BusinessException(PortUserMessageConstant.USER_ID_CANNOT_BE_EMPTY);
        }

        try {
            // 业务规则校验：检查用户是否存在
            PortUser portUser = portUserMapper.selectById(userId);
            if (portUser == null) {
                throw new BusinessException(PortUserMessageConstant.USER_NOT_FOUND);
            }

            portUserMapper.deleteById(userId);
//        userMapper.deleteById(userId);
        } catch (BusinessException e) {
            // 业务异常直接抛出
            throw e;
        } catch (DataIntegrityViolationException e) {
            log.error("删除港口人员失败，数据完整性约束异常：{}", e.getMessage());
            throw new BusinessException("删除失败，该港口人员存在关联数据，请先删除关联数据");
        } catch (Exception e) {
            log.error("删除港口人员失败，未知异常：{}", e.getMessage(), e);
            throw new BusinessException(PortUserMessageConstant.DELETE_FAILED);
        }
    }

    /**
     * 港口人员分页查询
     * @param portUserPageQueryDTO 分页查询条件
     * @return 分页结果
     */
    public PageResult userPageQuery(PortUserPageQueryDTO portUserPageQueryDTO) {
        try {
            // 参数解析
            int pageNum = portUserPageQueryDTO.getPage();
            int pageSize = portUserPageQueryDTO.getPageSize();

            // 业务规则校验：分页参数校验
            if (pageNum < 1) {
                throw new BusinessException("页码必须大于0");
            }
            if (pageSize < 1 || pageSize > 100) {
                throw new BusinessException("每页数量必须在1-100之间");
            }

            // 构造分页对象
            Page<PortUser> page = new Page<>(pageNum, pageSize);

            // 构造查询条件
            LambdaQueryWrapper<PortUser> wrapper = new LambdaQueryWrapper<>();

            if (portUserPageQueryDTO.getUserType() != null && !portUserPageQueryDTO.getUserType().isEmpty()) {
                wrapper.eq(PortUser::getUserType, portUserPageQueryDTO.getUserType());
            }

            if (portUserPageQueryDTO.getPortId() != null && !portUserPageQueryDTO.getPortId().isEmpty()) {
                wrapper.eq(PortUser::getPortId, portUserPageQueryDTO.getPortId());
            }

            // 执行分页查询
            Page<PortUser> resultPage = this.portUserMapper.selectPage(page, wrapper);

            // 封装结果
            PageResult pageResult = new PageResult();
            pageResult.setTotal(resultPage.getTotal());
            pageResult.setRecords(resultPage.getRecords());
            return pageResult;
        } catch (BusinessException e) {
            // 业务异常直接抛出
            throw e;
        } catch (Exception e) {
            log.error("分页查询港口人员失败，未知异常：{}", e.getMessage(), e);
            throw new BusinessException(PortUserMessageConstant.QUERY_FAILED);
        }
    }

    @Override
    public void userUpdate(PortUserDTO portUserDTO) {
        try {
            // 1. 业务规则校验：username 不能为空
            String username = portUserDTO.getUsername();
            if (username == null || username.trim().isEmpty()) {
                throw new BusinessException(PortUserMessageConstant.USERNAME_CANNOT_BE_EMPTY);
            }

            // 2. 根据 username 查询原始用户（获取雪花算法生成的 userId）
            QueryWrapper<PortUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username); // 利用唯一约束查询
            PortUser originalUser = portUserMapper.selectOne(queryWrapper);

            // 3. 业务规则校验：用户是否存在
            if (originalUser == null) {
                throw new BusinessException(PortUserMessageConstant.USER_NOT_FOUND);
            }

            // 4. 构建更新实体（复制 portUserDTO 中的可修改字段，保留原始 userId）
            PortUser portUser = new PortUser();
            BeanUtils.copyProperties(portUserDTO,portUser);
            portUser.setUserId(originalUser.getUserId()); // 必须设置主键，用于定位修改

            portUserMapper.updateById(portUser);
        } catch (BusinessException e) {
            // 业务异常直接抛出
            throw e;
        } catch (DataIntegrityViolationException e) {
            log.error("修改港口人员失败，数据完整性约束异常：{}", e.getMessage());
            throw new BusinessException(PortUserMessageConstant.UPDATE_FAILED);
        } catch (Exception e) {
            log.error("修改港口人员失败，未知异常：{}", e.getMessage(), e);
            throw new BusinessException(PortUserMessageConstant.UPDATE_FAILED);
        }
    }


}
